package cn.anxingongyou.anxin.controller;

import cn.anxingongyou.anxin.utils.QiniuUtil;
import cn.anxingongyou.anxin.utils.Result;
import com.qiniu.common.QiniuException;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping(value = "/qiniu")
public class QiniuUploadController {

    private static Logger logger = LoggerFactory.getLogger(QiniuUploadController.class);

    @Resource
    private QiniuUtil qiniuUtil;

    @ApiOperation("上传图片文件")
    @ApiResponses({
            @ApiResponse(code = 200,message = "上传成功"),
            @ApiResponse(code = 406,message = "请选择文件"),
            @ApiResponse(code = 500,message = "上传失败")
    })
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    @ResponseBody
    public Map uploadImg(@ApiParam(value = "文件", required = true) @RequestParam("file") MultipartFile file) {
        return upload(file, 1);
    }

    @ApiOperation("上传视频文件")
    @ApiResponses({
            @ApiResponse(code = 200,message = "上传成功"),
            @ApiResponse(code = 406,message = "请选择文件"),
            @ApiResponse(code = 500,message = "上传失败")
    })
    @RequestMapping(value = "/uploadVideo", method = RequestMethod.POST)
    @ResponseBody
    public Map uploadVideo(@ApiParam(value = "文件", required = true) @RequestParam("file") MultipartFile file) {
        return upload(file, 0);
    }

    @ApiOperation("删除文件")
    @ApiResponses({
            @ApiResponse(code = 204,message = "删除成功"),
            @ApiResponse(code = 500,message = "删除失败")
    })
    @RequestMapping(value = "/delfile",method = RequestMethod.GET)
    @ResponseBody
    public Map delFile(@RequestParam(value = "filepath",required = true) @ApiParam(value = "文件路径，除域名之外的部分") String filepath){
        boolean isdel = false;
        try {
            isdel = qiniuUtil.delete(filepath);

        } catch (QiniuException e) {
            e.printStackTrace();
        }
        if(isdel){
            return Result.instance(204,"删除成功").toJsonMap();
        }else {
            return Result.instance(500,"删除失败").toJsonMap();
        }
    }

    /**
     * 上传七牛云
     * @param file 文件
     * @return json
     */
    public Map upload(MultipartFile file, int isImg){
        if (file.isEmpty()) {
            return Result.instance(406,"请选择文件").toJsonMap();
        }
        try {
            FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String fileExtend = originalFilename.substring(originalFilename.lastIndexOf("."));
            //默认不指定key的情况下，以文件内容的hash值作为文件名
            String fileKey = null;
            if(isImg == 1){
                 fileKey = "images/" + UUID.randomUUID().toString().replace("-", "") + fileExtend;
            }else {
                 fileKey = "video/" + UUID.randomUUID().toString().replace("-", "") + fileExtend;
            }
            String path = qiniuUtil.upload(fileInputStream,fileKey);
            Map<String, Object> res = new HashMap<>();
            res.put("url", path);
            return Result.<Map<String, Object>>instance(200,"上传成功", res).toJsonMap();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.instance(500,"上传失败").toJsonMap();
        }
    }
}
